﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Easydp.Models.Entities;
using Easydp.Controllers;
using System.Configuration;
using System.Text;
using System.IO;
namespace Web.Views.AilPay
{
    public partial class AliPay : System.Web.UI.Page
    {
        TT_Orders orderObj;
        TT_PushFee pushfeeObj;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(Request.Form["ctl00$ContentPlace$OrderID"]))
                    Response.Redirect("../Shared//ErrorPage.aspx?Error=parameter_error");
                OrderController orderControl = new OrderController();
                orderObj = orderControl.GetWaitPayOrder(Request.Form["ctl00$ContentPlace$OrderID"].ToString());
                pushfeeObj = (new PushFeeController()).GetModel(Convert.ToInt32(Request.Form["ctl00$ContentPlace$OrderID"]));
                if (orderObj == null)
                    Response.Redirect("../Shared//ErrorPage.aspx?Error=object_null");
                BindPayData();
            }
        }
        
        private void BindPayData()
        {
           AccountInfoController accountInfo = new AccountInfoController();
           TT_AccountInfo accountObj= accountInfo.GetModel(orderObj.AgentID);

           #region 业务参数赋值
           //按时构造订单号;
           //System.DateTime currentTime = new System.DateTime();
           //currentTime = System.DateTime.Now;
           //string out_trade_no = currentTime.ToString("g");
           //out_trade_no = out_trade_no.Replace("-", "");
           //out_trade_no = out_trade_no.Replace(":", "");
           //out_trade_no = out_trade_no.Replace(" ", "");
           //业务参数赋值；
            string gateway = "https://www.alipay.com/cooperate/gateway.do?";//'支付接口
            string service = "create_direct_pay_by_user";

            string sign_type = "MD5";
            string subject ="火车票";	//subject		商品名称
            string body = string.Format("订单号:{0},行程:{1}-{2}",orderObj.OrderNum,orderObj.StartStation,orderObj.EndStation) ;		//body			商品描述    
            string payment_type ="1";             //支付类型	
            string total_fee = orderObj.PayMoney.ToString("F"); //总金额					0.01～50000.00
            string show_url = "http://www.easydp.net";
            string seller_email = accountObj.AccountCode;   //卖家账号
            //string partner = "";//partner		合作伙伴ID			保留字段
            //string key = "zhiasv6quoplnykcii4vo3iv3afvh6si";              //partner账户的支付宝安全校验码

            //测试帐户
            //string partner =  "2088002061866935";                        //partner		合作伙伴ID			保留字段
            //string key ="btfhyepobkdkemcxtk2m74tmt85vjnzh";              //partner账户的支付宝安全校验码


            string partner = "2088002166377983";                        //partner		合作伙伴ID			保留字段
            string key = "zhiasv6quoplnykcii4vo3iv3afvh6si";              //partner账户的支付宝安全校验码

            string merchantCallbackURL = "";
            string NotifyType = ConfigurationManager.AppSettings["NotifyType"];
            string buyer_email = "";
            if (NotifyType == "域名")
            {
                merchantCallbackURL = "http://" + Request.Url.Authority + "/Views/AilPay/AliPayReceive.aspx|http://" + Request.Url.Authority + "/Views/AilPay/AliPayNotify.aspx";
            }
            else
            {
                string IPAddress = ConfigurationManager.AppSettings["IPAddress"];
                merchantCallbackURL = "http://" + IPAddress + "/Views/AilPay/AliPayReceive.aspx|http://" + IPAddress + "/Views/AilPay/AliPayNotify.aspx";
            }

            string return_url = merchantCallbackURL.Split(new char[] { '|' })[0].ToString();				//服务器通知返回接口
            string notify_url = merchantCallbackURL.Split(new char[] { '|' })[1].ToString();				//服务器通知返回接口     

            //string return_url = "http://localhost/easydp/Views/AilPay/AliPayReceive.aspx";
            //string notify_url = "http://localhost/easydp/Views/AilPay/AliPayNotify.aspx";			//服务器通知返回接口     
          

            string out_trade_no = orderObj.OrderNum;

            //提成信息
            string royalty_type = string.Empty;
            //获得订单的提成信息
            string royalty_parameter = string.Empty;
            string parameter = GetRoyaltyParameter();

            if (parameter.Length > 0)
            {
                royalty_parameter = parameter.ToString();
                royalty_type = "10";
            }
            
          
            // https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8&body=%e4%b8%ad%e6%96%87%e6%b5%8b%e8%af%95&notify_url=Alipay_Notify.aspx&out_trade_no=200904172117&partner=2088002061866935&payment_type=1&return_url=Alipay_Return.aspx&seller_email=panbbb%40126.com&service=create_direct_pay_by_user&show_url=www.alipay.com&subject=utf-8%e4%b8%ad%e6%96%87%e6%b5%8b%e8%af%95&total_fee=0.02&sign=c6a1522ae8cf7b1fe5f422b57a10d26f&sign_type=MD5
            //https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8&body=%e8%ae%a2%e5%8d%95%e5%8f%b7%3a0904170004%2c%e8%a1%8c%e7%a8%8b%3a%e6%88%90%e9%83%bd-%e5%b9%bf%e5%b7%9e&notify_url=http%3a%2f%2flocalhost%2feasydp%2fViews%2fAilPay%2fAliPayNotify.aspx&out_trade_no=0904170004&partner=2088002061866935&payment_type=1&return_url=http%3a%2f%2flocalhost%2feasydp%2fViews%2fAilPay%2fAliPayReceive.aspx&royalty_parameters=easydp%40yeah.net%5e10.00%5e%e7%81%ab%e8%bd%a6%e7%a5%a8%7cpanbbb%40hotmail.com%5e90.00%5e%e5%b9%b3%e5%8f%b0%e4%ba%a4%e6%98%93%e8%b4%b90904170004&royalty_type=10&seller_email=easydp%40yeah.net&service=create_direct_pay_by_user&show_url=http%3a%2f%2fwww.easydp.net&subject=%e7%81%ab%e8%bd%a6%e7%a5%a8&total_fee=100.00&sign=cd5facf7614451d6050cedfb2c946298&sign_type=MD5
            //https://www.alipay.com/cooperate/gateway.do?
            //body=订单号:0904170004,行程:成都-广州
            //&notify_url=http://localhost/easydp/Views/AilPay/AliPayNotify.aspx
            //&out_trade_no=0904170004
            //&partner=2088002061866935
            //&payment_type=1
            //&return_url=http://localhost/easydp/Views/AilPay/AliPayReceive.aspx
            //&royalty_parameters=easydp@yeah.net^0.01^1张price:130.00other:3.00Total:137.00actual:0.01|panbbb@hotmail.com^0.01^平台交易费;orderid:0904170004

            //&royalty_type=10
            //&seller_email=easydp@yeah.net
            //&service=create_direct_pay_by_user
            //&show_url=http://www.easydp.net
            //&subject=火车票
            //&total_fee=0.02
            //&sign=9354529dbb0f5afb1d47598fa554ed92
            //&sign_type=MD5
             AliPayCode ap = new AliPayCode();
            string aliay_url = ap.CreatUrl(
                gateway,
                service,
                partner,
                sign_type,
                out_trade_no,
                subject,
                body,
                payment_type,
                total_fee,
                show_url,
                seller_email,
                key,
                return_url,
                notify_url,
                royalty_type,
                royalty_parameter
                );
            //写入日志   
            StringBuilder meg = new StringBuilder("\r\n开始支付:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";订单号:" + orderObj.OrderID + ";向支付宝发送支付请求,url:" + aliay_url);
            //try
            //{
            //    //更新订单
            //    meg.AppendLine("数据库写入成功!");
            //}
            //catch (Exception ex)
            //{
            //    meg.AppendLine("数据库写入失败:");
            //    meg.Append(ex.Message);
            //}
            AliPayCode.WriteLog(meg.ToString(), LogType.AliPayLog);
            Response.Redirect(aliay_url);
            #endregion
        }
        private string GetRoyaltyParameter()
        {
            //&royalty_parameters=easydp@yeah.net^10.00^1张price:130.00other:3.00Total:137.00actual:10.00|panbbb@hotmail.com^90.00^平台交易费;orderid:0904170004
            StringBuilder parameter = new StringBuilder();
            if (pushfeeObj != null)
            {
                //售票点分账
               // parameter.AppendFormat("{0}^{1}",pushfeeObj.AgentAccount,pushfeeObj.AgentGet.ToString("F"));
               // decimal agentGet = orderObj.Amount * orderObj.UnitPrice + 4 + orderObj.TotalMoney;
               //// parameter.AppendFormat("^{0}张price:{1}other:{2}Total:{3}actual:{4}", orderObj.Amount, orderObj.UnitPrice, orderObj.TotalMoney, agentGet, pushfeeObj.AgentGet);
               // parameter.Append("^火车票");
                //平台分润
                if (pushfeeObj.AgentGet > 0 && !string.IsNullOrEmpty(pushfeeObj.PlatformAccount))
                {
                    parameter.AppendFormat("{0}^{1}^{2}", pushfeeObj.PlatformAccount, pushfeeObj.PlatformGet.ToString("F"), "平台交易费" + orderObj.OrderNum);
                }
                if (pushfeeObj.OtherGet > 0 && !string.IsNullOrEmpty(pushfeeObj.OtherAccount))
                {
                    //其他支付费用
                    if (parameter.ToString() != "")
                        parameter.Append("|");
                    parameter.AppendFormat("{0}^{1}^{2}", pushfeeObj.OtherAccount, pushfeeObj.OtherGet, "支付费用" + orderObj.OrderNum);
                }
            }
            return parameter.ToString();

        }



        
    }
}
